Imports System.Data.OleDb


''' <summary>
''' Provides functionality to load the data into the Files table in the Access database
''' </summary>
''' <remarks></remarks>
Public Class FileLoader

    Public Enum SplitterLocation
        StartOfFileName
        EndOfFileName
        None
    End Enum

    Public Enum SplitterType
        Dash
        Space
        Underscore
        SecondDash
        SecondUnderscore
        SecondSpace
        UnderscoreNoSpaces
        SecondUnderscoreNoSpaces
        DashNoSpaces
        SecondDashNoSpaces
        UserDefined
    End Enum

    Private Const InsertSql As String = "INSERT INTO Files (filename, code, provider, disc, actual_location) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')"
    Private Const LinkInsertSql As String = "INSERT INTO Files (filename, code, provider, disc, product_link, actual_location) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')"

    Private Const SingleQuote As String = "'"
    Private Const Apostrophe As String = "`"
    Private Const Period As String = "."

    Private Const BlankCode As String = " "
    Private Const Empty As String = ""

    Private Const Separator As String = "\"

    Private _conn As New OleDbConnection

    Private _fa As New ProductsTableAdapters.FilesTableAdapter

    Public Sub New()


    End Sub

    Private Function DecodeSplitterType(ByVal splitter As SplitterType) As String

        Dim splitterValue As String = ""

        Select Case splitter
            Case SplitterType.Dash, SplitterType.SecondDash
                splitterValue = " - "
            Case SplitterType.Space, SplitterType.SecondSpace
                splitterValue = " "
            Case SplitterType.Underscore, SplitterType.SecondUnderscore
                splitterValue = " _ "
            Case SplitterType.UnderscoreNoSpaces, SplitterType.SecondUnderscoreNoSpaces
                splitterValue = "_"
            Case SplitterType.DashNoSpaces, SplitterType.SecondDashNoSpaces
                splitterValue = "-"
        End Select

        Return splitterValue

    End Function

    Private Sub AddFile(ByVal filename As String, _
                        ByVal code As String, _
                        ByVal providerName As String, _
                        ByVal disc As String, _
                        ByVal filePath As String)

        Dim insertFileCommand As New OleDb.OleDbCommand
        insertFileCommand.Connection = _conn
        insertFileCommand.CommandType = CommandType.Text

        insertFileCommand.CommandText = String.Format(InsertSql, _
                                                      filename, _
                                                      code, _
                                                      providerName, _
                                                      disc, _
                                                      filePath)
        insertFileCommand.ExecuteNonQuery()

    End Sub

    Private Sub AddFile(ByVal filename As String, _
                        ByVal code As String, _
                        ByVal providerName As String, _
                        ByVal disc As String, _
                        ByVal url As String, _
                        ByVal filePath As String)

        Dim insertFileCommand As New OleDb.OleDbCommand
        insertFileCommand.Connection = _conn
        insertFileCommand.CommandType = CommandType.Text

        insertFileCommand.CommandText = String.Format(LinkInsertSql, _
                                                      filename, _
                                                      code, _
                                                      providerName, _
                                                      disc, _
                                                      url, _
                                                      filePath)

        insertFileCommand.ExecuteNonQuery()

    End Sub

    Private Sub SplitFileName(ByVal fullFileName As String, _
                              ByVal splitterType As String, _
                              ByVal location As SplitterLocation, _
                              ByVal findSecondOccurance As Boolean, _
                              ByRef code As String, _
                              ByRef filename As String)


        Dim splitterPosition As Integer = -1

        Select Case location

            Case SplitterLocation.StartOfFileName
                splitterPosition = fullFileName.IndexOf(splitterType)
                If findSecondOccurance Then
                    splitterPosition = fullFileName.IndexOf(splitterType, splitterPosition + 1)
                End If
                If splitterPosition = -1 Then
                    filename = fullFileName.Trim
                    code = BlankCode
                Else
                    code = fullFileName.Substring(0, splitterPosition)
                    filename = fullFileName.Substring(splitterPosition + splitterType.Length)
                End If

            Case SplitterLocation.EndOfFileName

                splitterPosition = fullFileName.LastIndexOf(splitterType)
                If splitterPosition = -1 Then
                    filename = fullFileName.Trim
                    code = BlankCode
                Else
                    filename = fullFileName.Substring(splitterPosition + splitterType.Length)
                    code = fullFileName.Substring(0, splitterPosition)
                End If

            Case SplitterLocation.None
                filename = fullFileName.Trim
                code = BlankCode
        End Select

        filename = filename.Replace(SingleQuote, Apostrophe)
        filename = filename.Substring(0, _
                                      filename.LastIndexOf(Period))
        code = code.Replace(SingleQuote, Apostrophe)

    End Sub

    Public Sub LoadFiles(ByVal filenames As Collections.ObjectModel.Collection(Of String), _
                         ByVal provider As String, _
                         ByVal disc As String, _
                         ByVal directory As String)

        Try

            _conn.ConnectionString = My.Settings.PoserFilesConnectionString
            _conn.Open()

            For Each fullFilename As String In filenames

                AddFile(fullFilename.Substring(0, _
                                               fullFilename.LastIndexOf(Period)), _
                        BlankCode, _
                        provider, _
                        disc, _
                        directory & Separator & fullFilename.Replace(SingleQuote, Apostrophe))

            Next

        Catch ex As OleDbException
            Throw
        Catch ex As Exception
            Throw
        Finally
            If _conn.State <> ConnectionState.Closed Then
                _conn.Close()
            End If
        End Try

    End Sub

    Public Sub LoadFiles(ByVal filenames As Collections.ObjectModel.Collection(Of String), _
                         ByVal provider As String, _
                         ByVal disc As String, _
                         ByVal splitter As SplitterType, _
                         ByVal location As SplitterLocation, _
                         ByVal noDuplicates As Boolean, _
                         ByVal directory As String)

        Dim url As String = ""
        Dim code As String = ""
        Dim filename As String = ""
        Dim useSecond As Boolean = False
        Dim duplicate As Boolean = False

        Dim splitterValue As String = DecodeSplitterType(splitter)

        If splitter = SplitterType.SecondDash Or _
            splitter = SplitterType.SecondDashNoSpaces Or _
            splitter = SplitterType.SecondSpace Or _
            splitter = SplitterType.SecondUnderscore Or _
            splitter = SplitterType.SecondUnderscoreNoSpaces Then

            useSecond = True

        End If

        Try

            _conn.ConnectionString = My.Settings.PoserFilesConnectionString
            _conn.Open()

            For Each fullFilename As String In filenames
                SplitFileName(fullFilename, _
                                    splitterValue, _
                                    location, _
                                    useSecond, _
                                    code, _
                                    filename)

                Select Case provider
                    Case ProviderNames.PoserPros
                        url = String.Format(PoserProsDownloader.BASE_PAGE_URL, _
                                            code.ToUpper.Replace(PoserProsDownloader.CODE_BASE, _
                                                                 Empty))
                    Case ProviderNames.Renderosity
                        url = String.Format(RenderosityDownloader.BASE_PAGE_URL, _
                                            code)
                    Case ProviderNames.ThreeDCommune
                        url = String.Format(ThreeDCommuneDownloader.BASE_PAGE_URL, _
                                            code.ToUpper.Replace(ThreeDCommuneDownloader.CODE_BASE, _
                                                                 Empty))
                    Case Else
                        url = ""
                End Select

                If noDuplicates And _
                   code <> BlankCode Then
                    duplicate = (CType(_fa.FileCountByCode(code, provider), Integer) > 0)
                End If

                If Not duplicate Then
                    AddFile(filename, _
                            code, _
                            provider, _
                            disc, _
                            url, _
                            directory & Separator & fullFilename.Replace(SingleQuote, Apostrophe))
                End If

            Next

        Catch ex As OleDbException
            Throw
        Catch ex As Exception
            Throw
        Finally
            If _conn.State <> ConnectionState.Closed Then
                _conn.Close()
            End If
        End Try


    End Sub

    Public Sub LoadFiles(ByVal filenames As Collections.ObjectModel.Collection(Of String), _
                         ByVal provider As String, _
                         ByVal disc As String, _
                         ByVal userSpecifiedSplitter As String, _
                         ByVal location As SplitterLocation, _
                         ByVal noDuplicates As Boolean, _
                         ByVal directory As String)

        Dim url As String = ""
        Dim code As String = ""
        Dim filename As String = ""
        Dim useSecond As Boolean = False
        Dim duplicate As Boolean = False

        Try

            _conn.ConnectionString = My.Settings.PoserFilesConnectionString
            _conn.Open()

            For Each fullFilename As String In filenames
                SplitFileName(fullFilename, _
                                    userSpecifiedSplitter, _
                                    location, _
                                    useSecond, _
                                    code, _
                                    filename)

                Select Case provider
                    Case ProviderNames.PoserPros
                        url = String.Format(PoserProsDownloader.BASE_PAGE_URL, _
                                            code.ToUpper.Replace(PoserProsDownloader.CODE_BASE, _
                                                                 Empty))
                    Case ProviderNames.Renderosity
                        url = String.Format(RenderosityDownloader.BASE_PAGE_URL, _
                                            code)
                    Case ProviderNames.ThreeDCommune
                        url = String.Format(ThreeDCommuneDownloader.BASE_PAGE_URL, _
                                            code.ToUpper.Replace(ThreeDCommuneDownloader.CODE_BASE, _
                                                                 Empty))
                    Case Else
                        url = ""
                End Select

                If noDuplicates And _
                   code <> BlankCode Then
                    duplicate = (CType(_fa.FileCountByCode(code, provider), Integer) > 0)
                End If

                If Not duplicate Then
                    AddFile(filename, _
                            code, _
                            provider, _
                            disc, _
                            url, _
                            directory & Separator & fullFilename.Replace(SingleQuote, Apostrophe))
                End If

            Next

        Catch ex As OleDbException
            Throw
        Catch ex As Exception
            Throw
        Finally
            If _conn.State <> ConnectionState.Closed Then
                _conn.Close()
            End If
        End Try


    End Sub


End Class
